﻿using OneCard.Face8280Module.Service;

namespace OneCard.Face8280Module.Worker
{
    /// <summary>
    /// 定时同步数据库人员、设备、权限操作
    /// </summary>
    public class SyncWorker
    {
        public static void Run(IServiceProvider service)
        {
            ILogger<SyncWorker> Logger = service.GetService<ILogger<SyncWorker>>();


            Task.Run(async () =>
            {
                do
                {

                    await Task.Delay(1000);


                    try
                    {
                        //定时同步数据库人员、设备、权限操作
                        //Logger.LogInformation("开始同步一卡通数据库操作时发生错误");

                        await RunWorker(service);
                    }
                    catch (Exception ex)
                    {

                        Logger.LogError($"同步一卡通数据库操作时发生错误：{ex.ToString()}");

                    }

                } while (true);
            });
        }

        /// <summary>
        /// 执行工作线程，开始同步操作
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        private static async Task RunWorker(IServiceProvider service)
        {
            DataService db;
            ILogger<SyncWorker> Logger = service.GetService<ILogger<SyncWorker>>();
            using (var scope = service.CreateScope())
            {
                var myService = scope.ServiceProvider;
                db = myService.GetService<DataService>();
                await db.SyncDatabase(Logger);
            }
        }
    }
}
